/**
 * 开发者管理页面JavaScript
 * 实现开发者的增删改查、搜索筛选等功能
 */

// 全局变量
let developers = [];
let filteredDevelopers = [];
let currentPage = 1;
const pageSize = 10;

// DOM元素
const developerContainer = document.getElementById('developerContainer');
const loadingSpinner = document.getElementById('loadingSpinner');
const emptyState = document.getElementById('emptyState');
const searchInput = document.getElementById('searchDeveloper');
const addDeveloperForm = document.getElementById('addDeveloperForm');
const editDeveloperForm = document.getElementById('editDeveloperForm');
const saveDeveloperBtn = document.getElementById('saveDeveloperBtn');
const updateDeveloperBtn = document.getElementById('updateDeveloperBtn');

// Toast元素
const successToast = new bootstrap.Toast(document.getElementById('successToast'));
const errorToast = new bootstrap.Toast(document.getElementById('errorToast'));
const successMessage = document.getElementById('successMessage');
const errorMessage = document.getElementById('errorMessage');

// 模态框
const addDeveloperModal = new bootstrap.Modal(document.getElementById('addDeveloperModal'));
const editDeveloperModal = new bootstrap.Modal(document.getElementById('editDeveloperModal'));

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
    bindEvents();
});

/**
 * 初始化页面
 */
function initializePage() {
    loadDevelopers();
}

/**
 * 绑定事件
 */
function bindEvents() {
    // 搜索功能
    searchInput.addEventListener('input', debounce(handleSearch, 300));
    document.getElementById('searchBtn').addEventListener('click', handleSearch);
    
    // 添加开发者
    saveDeveloperBtn.addEventListener('click', handleAddDeveloper);
    
    // 更新开发者
    updateDeveloperBtn.addEventListener('click', handleUpdateDeveloper);
    
    // 表单重置 - 仅在用户取消时重置
    document.getElementById('addDeveloperModal').addEventListener('hidden.bs.modal', function(e) {
        // 如果不是通过成功提交关闭的，才重置表单
        if (!e.target.dataset.successSubmit) {
            addDeveloperForm.reset();
            addDeveloperForm.classList.remove('was-validated');
        }
        // 清除标记
        delete e.target.dataset.successSubmit;
    });
    
    document.getElementById('editDeveloperModal').addEventListener('hidden.bs.modal', function() {
        editDeveloperForm.reset();
        editDeveloperForm.classList.remove('was-validated');
    });
    
    // 全局搜索
    document.getElementById('globalSearch').addEventListener('input', function(e) {
        if (e.target.value.trim()) {
            // 这里可以实现全局搜索功能
            console.log('全局搜索:', e.target.value);
        }
    });
}

/**
 * 加载开发者列表
 */
async function loadDevelopers() {
    try {
        showLoading(true);
        const response = await fetch('/api/developers');
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        developers = await response.json();
        filteredDevelopers = [...developers];
        renderDevelopers();
        
    } catch (error) {
        console.error('加载开发者列表失败:', error);
        showError('加载开发者列表失败，请刷新页面重试');
    } finally {
        showLoading(false);
    }
}

/**
 * 渲染开发者列表
 */
function renderDevelopers() {
    if (filteredDevelopers.length === 0) {
        showEmptyState(true);
        return;
    }
    
    showEmptyState(false);
    
    const html = filteredDevelopers.map(developer => createDeveloperCard(developer)).join('');
    developerContainer.innerHTML = html;
    
    // 添加淡入动画
    developerContainer.querySelectorAll('.developer-card').forEach((card, index) => {
        card.style.animationDelay = `${index * 0.1}s`;
        card.classList.add('fade-in');
    });
}

/**
 * 创建开发者卡片HTML
 */
function createDeveloperCard(developer) {
    const avatar = getAvatarText(developer.name);
    const statusClass = getStatusClass(developer.status);
    const roleClass = getRoleClass(developer.role);
    const statusText = getStatusText(developer.status);
    const roleText = getRoleText(developer.role);
    
    return `
        <div class="developer-card" data-developer-id="${developer.id}">
            <div class="d-flex align-items-start">
                <div class="developer-avatar">
                    ${avatar}
                </div>
                <div class="developer-info">
                    <div class="developer-name">
                        ${escapeHtml(developer.name)}
                        <span class="role-badge ${roleClass}">${roleText}</span>
                    </div>
                    <div class="developer-role">${roleText}</div>
                    <div class="developer-meta">
                        <span class="status-badge ${statusClass}">${statusText}</span>
                        <span><i class="bi bi-calendar"></i> 加入时间: ${formatDate(developer.createdAt)}</span>
                        ${developer.lastActiveAt ? `<span><i class="bi bi-clock"></i> 最后活跃: ${formatDate(developer.lastActiveAt)}</span>` : ''}
                    </div>
                </div>
                <div class="developer-actions">
                    <button class="btn btn-outline-primary btn-sm" onclick="editDeveloper('${developer.id}')" title="编辑">
                        <i class="bi bi-pencil"></i>
                    </button>

                    <div class="dropdown">
                        <button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="bi bi-three-dots"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#" onclick="changeStatus('${developer.id}', 'ACTIVE')">设为活跃</a></li>
                            <li><a class="dropdown-item" href="#" onclick="changeStatus('${developer.id}', 'BUSY')">设为忙碌</a></li>
                            <li><a class="dropdown-item" href="#" onclick="changeStatus('${developer.id}', 'ON_LEAVE')">设为请假</a></li>
                            <li><a class="dropdown-item" href="#" onclick="changeStatus('${developer.id}', 'INACTIVE')">设为非活跃</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="#" onclick="deleteDeveloper('${developer.id}')">删除</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    `;
}

/**
 * 处理搜索
 */
function handleSearch() {
    const query = searchInput.value.trim().toLowerCase();
    
    if (!query) {
        filteredDevelopers = [...developers];
    } else {
        filteredDevelopers = developers.filter(developer => 
            developer.name.toLowerCase().includes(query) ||
            getRoleText(developer.role).toLowerCase().includes(query) ||
            getStatusText(developer.status).toLowerCase().includes(query)
        );
    }
    
    renderDevelopers();
}

/**
 * 处理添加开发者
 */
async function handleAddDeveloper() {
    if (!addDeveloperForm.checkValidity()) {
        addDeveloperForm.classList.add('was-validated');
        return;
    }
    
    const formData = new FormData(addDeveloperForm);
    const developerData = {
        id: document.getElementById('developerId').value.trim(),
        name: document.getElementById('developerName').value.trim(),
        role: document.getElementById('developerRole').value
    };
    
    try {
        saveDeveloperBtn.disabled = true;
        saveDeveloperBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>保存中...';
        
        const response = await fetch('/api/developers', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(developerData)
        });
        
        if (!response.ok) {
            const error = await response.text();
            throw new Error(error || '添加开发者失败');
        }
        
        const newDeveloper = await response.json();
        developers.unshift(newDeveloper);
        filteredDevelopers = [...developers];
        
        // 标记为成功提交，然后关闭模态框
        document.getElementById('addDeveloperModal').dataset.successSubmit = 'true';
        addDeveloperModal.hide();
        renderDevelopers();
        showSuccess('开发者添加成功！');
        
    } catch (error) {
        console.error('添加开发者失败:', error);
        showError(error.message || '添加开发者失败，请重试');
    } finally {
        saveDeveloperBtn.disabled = false;
        saveDeveloperBtn.innerHTML = '保存';
    }
}

/**
 * 编辑开发者
 */
function editDeveloper(developerId) {
    const developer = developers.find(d => d.id === developerId);
    if (!developer) {
        showError('开发者不存在');
        return;
    }
    
    document.getElementById('editDeveloperId').value = developer.id;
    document.getElementById('editDeveloperName').value = developer.name;
    document.getElementById('editDeveloperRole').value = developer.role;
    document.getElementById('editDeveloperStatus').value = developer.status;
    
    editDeveloperModal.show();
}

/**
 * 处理更新开发者
 */
async function handleUpdateDeveloper() {
    if (!editDeveloperForm.checkValidity()) {
        editDeveloperForm.classList.add('was-validated');
        return;
    }
    
    const developerId = document.getElementById('editDeveloperId').value;
    const developerData = {
        name: document.getElementById('editDeveloperName').value.trim(),
        role: document.getElementById('editDeveloperRole').value,
        status: document.getElementById('editDeveloperStatus').value
    };
    
    try {
        updateDeveloperBtn.disabled = true;
        updateDeveloperBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>更新中...';
        
        const response = await fetch(`/api/developers/${developerId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(developerData)
        });
        
        if (!response.ok) {
            const error = await response.text();
            throw new Error(error || '更新开发者失败');
        }
        
        const updatedDeveloper = await response.json();
        const index = developers.findIndex(d => d.id === developerId);
        if (index !== -1) {
            developers[index] = updatedDeveloper;
            filteredDevelopers = [...developers];
        }
        
        editDeveloperModal.hide();
        renderDevelopers();
        showSuccess('开发者信息更新成功！');
        
    } catch (error) {
        console.error('更新开发者失败:', error);
        showError(error.message || '更新开发者失败，请重试');
    } finally {
        updateDeveloperBtn.disabled = false;
        updateDeveloperBtn.innerHTML = '更新';
    }
}

/**
 * 更改开发者状态
 */
async function changeStatus(developerId, newStatus) {
    try {
        const response = await fetch(`/api/developers/${developerId}/status`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ status: newStatus })
        });
        
        if (!response.ok) {
            throw new Error('状态更新失败');
        }
        
        const updatedDeveloper = await response.json();
        const index = developers.findIndex(d => d.id === developerId);
        if (index !== -1) {
            developers[index] = updatedDeveloper;
            filteredDevelopers = [...developers];
        }
        
        renderDevelopers();
        showSuccess('状态更新成功！');
        
    } catch (error) {
        console.error('状态更新失败:', error);
        showError('状态更新失败，请重试');
    }
}

/**
 * 删除开发者
 */
async function deleteDeveloper(developerId) {
    if (!confirm('确定要删除这个开发者吗？此操作不可撤销。')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/developers/${developerId}`, {
            method: 'DELETE'
        });
        
        if (!response.ok) {
            throw new Error('删除失败');
        }
        
        developers = developers.filter(d => d.id !== developerId);
        filteredDevelopers = [...developers];
        
        renderDevelopers();
        showSuccess('开发者删除成功！');
        
    } catch (error) {
        console.error('删除开发者失败:', error);
        showError('删除失败，请重试');
    }
}



/**
 * 工具函数
 */

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 获取头像文字
function getAvatarText(name) {
    if (!name) return '?';
    const words = name.trim().split(' ');
    if (words.length >= 2) {
        return (words[0][0] + words[1][0]).toUpperCase();
    }
    // 显示名字的后两个字
    return name.length >= 2 ? name.substring(name.length - 2).toUpperCase() : name.toUpperCase();
}

// 获取状态样式类
function getStatusClass(status) {
    const statusMap = {
        'ACTIVE': 'status-active',
        'BUSY': 'status-busy',
        'ON_LEAVE': 'status-on-leave',
        'INACTIVE': 'status-inactive'
    };
    return statusMap[status] || 'status-inactive';
}

// 获取角色样式类
function getRoleClass(role) {
    const roleMap = {
        'JUNIOR_DEVELOPER': 'role-junior',
        'DEVELOPER': 'role-developer',
        'SENIOR_DEVELOPER': 'role-senior',
        'TECH_LEAD': 'role-lead',
        'ARCHITECT': 'role-architect',
        'PROJECT_MANAGER': 'role-manager'
    };
    return roleMap[role] || 'role-developer';
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'ACTIVE': '活跃',
        'BUSY': '忙碌',
        'ON_LEAVE': '请假',
        'INACTIVE': '非活跃'
    };
    return statusMap[status] || '未知';
}

// 获取角色文本
function getRoleText(role) {
    const roleMap = {
        'JUNIOR_DEVELOPER': '初级开发者',
        'DEVELOPER': '开发者',
        'SENIOR_DEVELOPER': '高级开发者',
        'TECH_LEAD': '技术负责人',
        'ARCHITECT': '架构师',
        'PROJECT_MANAGER': '项目经理'
    };
    return roleMap[role] || '开发者';
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

// HTML转义
function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

// 显示加载状态
function showLoading(show) {
    loadingSpinner.style.display = show ? 'block' : 'none';
    developerContainer.style.display = show ? 'none' : 'block';
}

// 显示空状态
function showEmptyState(show) {
    emptyState.style.display = show ? 'block' : 'none';
    developerContainer.style.display = show ? 'none' : 'block';
}

// 显示成功消息
function showSuccess(message) {
    successMessage.textContent = message;
    successToast.show();
}

// 显示错误消息
function showError(message) {
    errorMessage.textContent = message;
    errorToast.show();
}

// 导出函数供全局使用
window.editDeveloper = editDeveloper;
window.deleteDeveloper = deleteDeveloper;
window.changeStatus = changeStatus;